package com.music.controller;

import com.music.pojo.SingleSong;
import com.music.service.SingleSongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
public class FileDownloadController {
    @Autowired
    private SingleSongService singleSongService;

    @RequestMapping("download")
    public void fileDown(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletContext application = request.getServletContext();

        SingleSong singleSong = singleSongService.findSingleSongById(id);
        String mimeType = application.getMimeType(singleSong.getSource());
        String fileName = singleSong.getMname();
        // 1.告诉浏览器, 文件类型是什么
        response.setContentType(mimeType); // mime类型 -> 修改的是响应头信息
        // 2.通知浏览器, 文件打开方式是什么 (附件形式打开)
        // 处理中文乱码
        String agent = request.getHeader("User-Agent");
        String name = getFileName(agent, fileName);
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        // URLDecoder   浏览器的解码器
        // URLEncoder   编码器, 将中文 -> %E7

        // 要下载的文件
        String filePath = application.getRealPath(singleSong.getSource());
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] bs = new byte[4096];
        int i;
        while ((i = bis.read(bs)) != -1) {
            out.write(bs, 0, i);
        }

        bis.close();
    }
    public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
        if (agent.contains("MSIE")) {
            // IE浏览器 %4E
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            // URLDecoder.decode(filename, "UTF-8");
        }
        return filename;
    }
}
